package com.example.myapplication.messenger;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

public class MessageService extends Service {
    final static String TAG = "messenger";
    final static int MSG_SAY_HELLO = 1;
    final static int MSG_SET_VALUE = 2;

    public MessageService(){
    }

    class IncomingHandler extends Handler{
        public void handleMessage(Message message){
            ///接收客户端发来的消息
            switch (message.what){
                case MSG_SAY_HELLO:
                    Toast.makeText(getApplicationContext(),"hello!"+message.getData().getString("data"),Toast.LENGTH_SHORT).show();
                    ///向客户端发送消息
                    Message msg = Message.obtain(null,MSG_SET_VALUE);
                    Bundle bundle = new Bundle();
                    bundle.putString("data2","很好");
                    msg.setData(bundle);

                    try {

                        Log.e(TAG, "replyTo: "+message.replyTo);
                        message.replyTo.send(msg);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }

                    ///来自客户端的信使，将消息发出去。


                    break;
            }
            super.handleMessage(message);
        }
    }

    Messenger messenger = new Messenger(new IncomingHandler());

    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind: ---------------------绑定成功");

        return messenger.getBinder();
    }
}
